package com.scoy.honeymei.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.HttpParams;
import com.scoy.honeymei.R;
import com.scoy.honeymei.activity.mall.GoodsDetailActivity;
import com.scoy.honeymei.activity.mall.GoodsListActivity;
import com.scoy.honeymei.activity.mall.ShopListActivity;
import com.scoy.honeymei.activity.mall.ShopMainActivity;
import com.scoy.honeymei.adapter.MallMainAdapter;
import com.scoy.honeymei.adapter.tabadapter.ViewPagerAdapter;
import com.scoy.honeymei.base.BaseFragment;
import com.scoy.honeymei.bean.BannerBean;
import com.scoy.honeymei.bean.CatePlateBean;
import com.scoy.honeymei.bean.CinemaBean;
import com.scoy.honeymei.bean.GoodsBean;
import com.scoy.honeymei.custem.PageMe;
import com.scoy.honeymei.databinding.FragmentMallMainBinding;
import com.scoy.honeymei.http.HpGo;
import com.scoy.honeymei.install.GridViewAdapter;
import com.scoy.honeymei.url.ApiCallBack;
import com.scoy.honeymei.url.MyUrl;
import com.scoy.honeymei.utils.MyUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: MallFragment$
 * @Description:
 * @Author: GaoZhan
 * @CreateDate: 2019/8/30/0030$ 上午 9:20$
 * @UpdateUser: 更新者
 * @UpdateDate: 2019/8/30/0030$ 上午 9:20$
 * @UpdateRemark: 更新内容
 */
public class MallMainFragment extends BaseFragment {


    private Context mContext;
    private FragmentMallMainBinding binding;
    private MallMainAdapter mallAdapter;
    private int pageInt = 1;
    private String orderStr = "";

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentMallMainBinding.inflate(inflater, container, false);
        View view = binding.getRoot();

        mContext = getContext();


        initNormal();

        getBanner();
        getCate();

        getGoodsList(1);


        return view;
    }

    @Override
    public void initNormal() {

        binding.titleLlt.setPadding(0, MyUtil.getStatusBarHeight(mContext), 0, 0);

        binding.fmmToticketIv.setVisibility(View.GONE);

        initRv();

        binding.fmmSearchTv.setOnClickListener(v -> {
            Intent intent0 = new Intent(mContext, GoodsListActivity.class);
            intent0.putExtra("cateId", 0);
            intent0.putExtra("pageType", 1);
            intent0.putExtra("shopId", 0);

            startActivity(intent0);
        });


        binding.norSrl.setOnRefreshListener(refreshLayout -> {

            refreshLayout.finishRefresh(1500);
            mallAdapter.clearData();
            getGoodsList(1);

        }).setOnLoadMoreListener(refreshLayout -> {
            refreshLayout.finishLoadMore(1500);
            getGoodsList(pageInt);
        });

        orderStr = "price";
        binding.fmmCheckpriceTv.setSelected(true);
        binding.fmmCheckpriceView.setSelected(true);
        binding.fmmCheckstarTv.setSelected(false);
        binding.fmmCheckstarView.setSelected(false);

        binding.fmmCheckpriceTv.setOnClickListener(v -> {
            if ("price".equals(orderStr)) return;
            orderStr = "price";
            binding.fmmCheckpriceTv.setSelected(true);
            binding.fmmCheckpriceView.setSelected(true);
            binding.fmmCheckstarTv.setSelected(false);
            binding.fmmCheckstarView.setSelected(false);
            binding.norSrl.autoRefresh();

        });
        binding.fmmCheckstarTv.setOnClickListener(v -> {
            if ("star".equals(orderStr)) return;
            orderStr = "star";
            binding.fmmCheckpriceTv.setSelected(false);
            binding.fmmCheckpriceView.setSelected(false);
            binding.fmmCheckstarTv.setSelected(true);
            binding.fmmCheckstarView.setSelected(true);
            binding.norSrl.autoRefresh();
        });

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    private void initRv() {
        mallAdapter = new MallMainAdapter(mContext);
        GridLayoutManager glm = new GridLayoutManager(mContext, 2, RecyclerView.VERTICAL, false);
        binding.fmmGoodsRv.setLayoutManager(glm);
        binding.fmmGoodsRv.setAdapter(mallAdapter);
        mallAdapter.setOnOneClick(pos -> {
            //to goods
            GoodsBean item = mallAdapter.getItem(pos);
            int id = item.getId();
            Intent intentde = new Intent(mContext, GoodsDetailActivity.class);
            intentde.putExtra("goodsId", id + "");
            startActivityForResult(intentde, 0x871);
        });
        mallAdapter.setOnTwoClick(pos -> {
            GoodsBean item = mallAdapter.getItem(pos);
            Intent intentde = new Intent(mContext, ShopMainActivity.class);
            intentde.putExtra("shopId", item.getShop_id());

            startActivity(intentde);

        });

    }

    private void getBanner() {
        HttpParams params = new HttpParams();
        HpGo.newInstance().HttpGo(getActivity(), MyUrl.BANNER_PLATE, params, new ApiCallBack() {
            @Override
            public void onSuccess(String body) {
                List<BannerBean> mlist = new Gson().fromJson(body, new TypeToken<List<BannerBean>>() {
                }.getType());
                PageMe.initBanner(getActivity(), binding.fmmBanner, mlist);
            }
        });
    }

    private void getCate() {
        HttpParams params = new HttpParams();
        HpGo.newInstance().HttpGo(getActivity(), MyUrl.CATE_PLATE, params, new ApiCallBack() {
            @Override
            public void onSuccess(String body) {
                List<CatePlateBean> mlist = new Gson().fromJson(body, new TypeToken<List<CatePlateBean>>() {
                }.getType());

                initGrid(mlist);
            }
        });

    }

    private void getGoodsList(int myPage) {
        if (myPage == -1) {
            MyUtil.mytoast(mContext, "没有更多了~");
            return;
        }
        HttpParams params = new HttpParams();
        params.put("shop_id", "");
        params.put("page", myPage);
        //排序:price=价格从低到高,star=星级从高到底,不填则默认创建时间
        params.put("order", orderStr);
        HpGo.newInstance().HttpGo(getActivity(), MyUrl.STORE_HOT_GOODS, params, new ApiCallBack() {
            @Override
            public void onSuccess(String body) {
                List<GoodsBean> mlist = new Gson().fromJson(body, new TypeToken<List<GoodsBean>>() {
                }.getType());

                mallAdapter.addData(mlist);
                pageInt = mlist.size() == 0 ? -1 : myPage + 1;
                binding.nodataTv.setVisibility(mallAdapter.getData().size() == 0 ? View.VISIBLE : View.GONE);
            }
        });

    }


    @Override
    public void onStart() {
        super.onStart();
        binding.fmmBanner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        binding.fmmBanner.stopAutoPlay();
    }

    /**
     * 总的页数
     */
    private int pageCount;
    /**
     * 每一页显示的个数
     */
    private int pageSize = 8;
    /**
     * 当前显示的是第几页
     */
    private int curIndex = 0;


    private void initGrid(List<CatePlateBean> cateList) {
        if (cateList == null || cateList.size() == 0) {
            binding.fmmCateVp.setVisibility(View.GONE);
            return;
        } else {
            binding.fmmCateVp.setVisibility(View.VISIBLE);
            cateList.add(0, new CatePlateBean(0, "全部", "", 0));
        }

        //总的页数=总数/每页数量，并取整
        pageCount = (int) Math.ceil(cateList.size() * 1.0 / pageSize);
        ArrayList<View> mPagerList = new ArrayList<View>();
        for (int i = 0; i < pageCount; i++) {
            // 每个页面都是inflate出一个新实例
            GridView gridView = (GridView) LayoutInflater.from(mContext).inflate(R.layout.gridview, binding.fmmCateVp, false);
            GridViewAdapter gridViewAdapter = new GridViewAdapter(mContext, cateList, i, pageSize);
            gridView.setAdapter(gridViewAdapter);
            mPagerList.add(gridView);
            gridViewAdapter.setOnOneClick(pos -> {
                CatePlateBean cateBean = cateList.get(pos);
                Intent intent0 = new Intent(mContext, ShopListActivity.class);
                intent0.putExtra("cateId", cateBean.getId());
                intent0.putExtra("title", cateBean.getName());
                startActivityForResult(intent0,0x871);
            });
        }

        //设置适配器
        binding.fmmCateVp.setAdapter(new ViewPagerAdapter(mPagerList));
        //设置圆点
        setOvalLayout();
        binding.mLlDot.setViewPager(binding.fmmCateVp);
    }


    /**
     * 设置圆点
     */
    public void setOvalLayout() {

     /*   for (int i = 0; i < pageCount; i++) {
            binding.mLlDot.addView(LayoutInflater.from(mContext).inflate(R.layout.btrmline, null));
        }
        // 默认显示第一页
        binding.mLlDot.getChildAt(0).findViewById(R.id.v_dot)
                .setBackgroundColor(getResources().getColor(R.color.colorMainRed));

        binding.fmmCateVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                // 取消圆点选中
                binding.mLlDot.getChildAt(curIndex)
                        .findViewById(R.id.v_dot)
                        .setBackgroundColor(getResources().getColor(R.color.colorMainGray3));
                // 圆点选中
                binding.mLlDot.getChildAt(position)
                        .findViewById(R.id.v_dot)
                        .setBackgroundColor(getResources().getColor(R.color.colorMainRed));
                curIndex = position;
            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });*/

    }


}
